const db = require('@/db/db-connection')
const { dateFormat } = require('@/utils/common.util')

class LoginLogModel {
  constructor () {
    this.tableName = 'login_log'
  }

  /**
   * find logs by userId
   * @param { String } userId
   * @returns
   */
  async find (userId, pageNo, pageSize) {
    try {
      const sql = `SELECT * FROM ${this.tableName} t WHERE t.userId = ? ORDER BY loginTime DESC LIMIT ${(pageNo - 1) * pageSize}, ${pageSize}`

      const totalSql = `SELECT COUNT(*) as total FROM ${this.tableName} t WHERE t.userId = ?`

      const list = await db.query(sql, [userId])

      const total = await db.query(totalSql, [userId])

      list.forEach(item => {
        item.ip = (item.ip || '').replace(/.$/, '*')
      })

      return {
        pageNo,

        pageSize,

        list,

        total: total[0].total
      }
    } catch (error) {
      throw new Error(error)
    }
  }

  /**
   * add tag
   * @param { String } name tagName
   * @param { String } folderId pid
   * @param { String } url userId userId
   */
  async add ({ userId, address, ip, loginType }) {
    try {
      const loginTime = dateFormat(new Date())

      const sql = `INSERT INTO ${this.tableName} (userId, loginTime, address, ip, loginType) VALUES(?, ?, ?, ?, ?)`

      await db.query(sql, [userId, loginTime, address, ip, loginType])
    } catch (error) {
      throw new Error(error)
    }
  }
}

module.exports = new LoginLogModel()
